<template>
  <el-form
    ref="loginForm"
    :model="loginFormData"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-loginFormData"
  >
    <el-form-item label="用户名" prop="username">
      <el-input
        v-model="loginFormData.username"
        type="input"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input
        v-model="loginFormData.password"
        type="password"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item label="验证码" prop="captcha" class="captchaname-from-item">
      <el-input
        v-model="loginFormData.captcha"
        @keydown.enter="submitForm(loginForm)"
        maxlength="5"
        class="captcha_input"
      />
      <div
        v-loading="loading"
        class="get-label"
        v-html="captcha"
        @click="getCaptcha"
      ></div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(loginForm)" class="login"
        >登录</el-button
      >
      <!-- <el-button @click="resetForm(loginForm)">Reset</el-button> -->
    </el-form-item>
  </el-form>
</template>
<script setup>
//引入接口
import * as api from "@/api/index.js";
import { reactive, ref, onMounted, onUnmounted } from "vue";
//引入校验函数
import { rules, useSubmitForm } from "../../composition/login/validate";
//引入路由对象
import { useRouter } from "vue-router";
//引入store
import { useUser } from "@/store/users";
//引入loading加载框
import { ElLoading } from "element-plus";

//使用路由对象
let router = useRouter();
//使用store
let userStore = useUser();

//控制Loading的显示和隐藏
let loading = ref(true);

//表单校验成功之后，回调的方法
let validateSuccess = () => {
  //发起登录请求

  //1.登录请求之前先校验验证码,将验证码转写成小写
  verifyCaptcha(loginFormData.captcha.toLowerCase());

  // console.log("校验成功");
};
//表单校验失败，回调的方法
let validateFailed = () => {
  console.log("校验失败");
};
//使用submitForm
let submitForm = useSubmitForm(validateSuccess, validateFailed);
const loginForm = ref();

//注入到表单的数据
const loginFormData = reactive({
  username: "", //用户
  password: "", //密码
  captcha: "", //验证码
});
//声明一个展示验证码的响应式变量
let captcha = ref();
//获取验证码
let getCaptcha = async () => {
  //发起请求，就打开loading
  loading.value = true;
  let res = await api.getCaptchaApi();
  //请求到了数据，关掉loading加载动画,
  loading.value = false;
  if (res.data.state) {
    captcha.value = res.data.img;
  }
};
//校验验证码
//1.本地的表单校验通过之后
//2.通过接口校验验证码,一定要配置代理
//3.声明loadingInstance，用户储存loading的动画实例
let loadingInstance = null
let verifyCaptcha = async (captcha) => {
    //发起登录请求的时候就要加载loading加载框
    loadingInstance = ElLoading.service({
    lock: true,
    text: "正在输入...",
    background: "rgba(0,0,0,.3)",
  });
  console.log(11, captcha);
  try {
    console.log(33);
    let res = await api.verifyCaptchaApi(captcha);
    console.log(22, res);
    //表示验证码通过
    //发起登录请求
    login(loginFormData.username, loginFormData.password);
  } catch (e) {
    console.log(444);
    // console.log(e);
    //验证码校验失败，需要重新刷新一个验证码
    getCaptcha();
    loadingInstance.close();//关掉加载动画框
  }
};

//用户密码登入逻辑
/**
 *
 * @param {String} username  用户名
 * @param {String} password  用户密码
 */
let login = async (username, password) => {

  try {
    //调用登入请求的接口
    let res = await api.loginApi(username, password);
    // console.log(res);
    //储存token，存到sessionStorage中
    sessionStorage.setItem("myx-token", res.data.token);
    //储存用户信息
    userStore.$patch({
      userInfo:res.data.userInfo
    });
    
    //登录成功需要跳转页面
    router.push("/");
  } catch (e) {
    console.log(e);
    loadingInstance.close();//关掉加载动画框
  }
};
onUnmounted(()=>{
  console.log('组件卸载了')
  //关掉加载动画框
  loadingInstance && loadingInstance.close();
})

//首次加载页面调用
onMounted(() => {
  getCaptcha();
});
</script>

<style lang="less" scoped>
:deep(.el-input__wrapper) {
  box-shadow: none;
}
.captcha_input {
  :deep(.el-input__wrapper) {
    border-radius: 4px 0 0 4px;
  }
}
</style>
